(function () {
    'use strict';

    angular.module('KingAdmin.pages.pdev.firmware')
        .controller('FirmwareListCtrl', FirmwareListCtrl);

    /** @ngInject */
    function FirmwareListCtrl($scope, $uibModal, $filter, FirmwareService, DeviceService, DictService) {

        var kt = this;
        kt.firmwarelist = [];
        kt.status = [];

        kt.LoadPage = function (tableState) {
            tableState = tableState || kt.tableState;
            tableState.pagination.number = tableState.pagination.number || 10;
            FirmwareService.getSmartData(tableState,
                function (data) {
                    tableState.pagination.numberOfPages = data.result.pages;
                    tableState.pagination.totalItemCount = data.result.total;
                    kt.tableState = tableState;
                    kt.firmwarelist = data.result.records;
                });
        };

        kt.showDevName = DeviceService.showDevName;
        kt.getDictLabel = DictService.getDictLabel;

        //删除
        kt.del = function (id) {
            FirmwareService.del({id: id},
                function (data) {
                    kt.LoadPage();
                })
        };
        kt.checkboxes = {
            checked: false,
            items: {}
        };

        kt.showFirmFile = function(id) {
            $uibModal.open({
                templateUrl: 'app/pages/pdev/firmware/firmware-file.html',
                controller: function ($scope,$uibModalInstance, FirmwareService) {
                    $scope.id = id;

                    console.log("fu:" + $scope.id);

                    $scope.save = function () {
                        var fd = new FormData();
                        var file = document.querySelector('input[type=file]').files[0];
                        fd.append('file', file);
                        fd.append('id', $scope.id);

                        console.log(fd);

                        FirmwareService.uploadFirmware(fd, function (data) {
                            console.log(data);
                            $uibModalInstance.close(true);
                        });
                    }
                },
                controllerAs: 'kt',
                backdrop: 'static',
                size: 'md'
            })
        };


        kt.upgradeDevFirm = function(firmId) {
            $uibModal.open({
                templateUrl: 'app/pages/pdev/firmware/upgrade-dev.html',
                controller: function ($scope, $interval, $uibModalInstance, toastr, FirmwareService, DeviceService) {
                    $scope.firmId = firmId;
                    kt = $scope;

                    $scope.processStyle = {
                        "width": "0%"
                    };
                    $scope.processText = '未开始';

                    $scope.devList = [];
                    DeviceService.getDictList(function (data) {
                        $scope.devList = data.result;
                        $scope.isShowDev = true;
                        $scope.devUid = '1243123413';
                    });

                    $scope.timer = null;

                    $scope.syncUpgProcess = function() {
                        DeviceService.getGateway($scope.devUid, function (data) {
                            if (data.result) {
                                console.log(data.result);

                                var firmFileSize = data.result.firmFileSize;
                                var curFirmIndex = data.result.curFirmIndex;

                                if (curFirmIndex == 0) {
                                    $scope.processStyle = {
                                        "width": "0%"
                                    };
                                    $scope.processText = '';
                                    return;
                                }

                                var per = (curFirmIndex / firmFileSize) * 100;

                                $scope.processStyle = {
                                    "width":  per + "%"
                                };

                                var frameCount = parseInt(firmFileSize / 900) + 1;
                                var curFrame = parseInt(curFirmIndex / 900);
                                $scope.processText = '升级中(' + curFrame + '/' + frameCount + ')';

                                console.log(firmFileSize);
                                console.log(curFirmIndex);
                                console.log(per);

                                if (firmFileSize <= curFirmIndex) {
                                    $scope.processText = '升级完成';
                                    console.log(per);

                                    // 升级完成取消定时器
                                    $interval.cancel($scope.timer);
                                }
                                console.log(per);
                            }
                        })
                    };


                    $scope.upgradeDevFirm = function () {
                        // 如果有定时器，取消定时器
                        if ($scope.timer) {
                            $interval.cancel($scope.timer);
                        }
                        $scope.devUid = kt.kt.deviceUid;

                        var param = {
                            firmId: $scope.firmId,
                            devUid: kt.kt.deviceUid
                        };

                        console.log(param);

                        FirmwareService.upgradeFirm(param, function (data) {

                            console.log(data);
                            if (data.code != '0') {
                                toastr.error(data.msg, "提示", {"progressBar": true,});
                                return;
                            }

                            // 开始监听更新状态
                            $scope.timer = $interval($scope.syncUpgProcess, 1000);

                            // $uibModalInstance.close(true);
                        });
                    };

                    // 离开页面清除timer
                    $scope.$on("$destroy", function() {
                        if ($scope.timer) {
                            $interval.cancel($scope.timer);
                        }
                    })
                },
                controllerAs: 'kt',
                backdrop: 'static',
                size: 'md'
            })
        };

        $scope.$watch('kt.checkboxes.checked', function (value) {
            angular.forEach(kt.userlist, function (item) {
                kt.checkboxes.items[item.id] = value;
            });
        });
    }

})();
